<template>
  <md-page
    isRefresh
    @pullDownRefresh="handlePullDownRefresh"
    :title="data.info.user_button_state !== TeamUserButtonState.领取参赛包 ? '选择尺码' : '领取参赛包'"
    isBtn
    backUrl="/pages/activity/index"
    :btnTextItems="data.btnTextItems"
    @btnClick="bottomBtnClick">
    <div class="container">
      <!-- 选择尺码表单 -->
      <uni-forms
        v-if="data.info.user_button_state == TeamUserButtonState.选择尺码 && data.way <= 0"
        ref="form"
        :modelValue="data.formData"
        label-position="top"
        label-width="100">
        <div class="item">
          <uni-forms-item label="领取方式" name="way">
            <uni-data-checkbox v-model="data.formData.way" :localdata="data.wayList"></uni-data-checkbox>
          </uni-forms-item>
        </div>
        <div class="item" v-if="data.formData.way == BagWayStatus.线上">
          <uni-forms-item
            label="地址"
            name="addr"
            required
            :rules="[
              {
                required: true,
                errorMessage: '请输入地址',
              },
            ]">
            <uni-easyinput
              disabled
              type="textarea"
              v-model="data.formData.addr"
              placeholder="请输入地址"
              suffixIcon="folder-add-filled"
              @iconClick="addrClick" />
          </uni-forms-item>
        </div>
        <view class="item">
          <view class="forms-item-label">
            <span style="color: red">*</span>
            尺码
          </view>
          <view class="form-item-content">
            <view class="member-list">
              <view class="member-item" v-for="(item, index) in data.formData.size_list" :key="index">
                <view
                  v-for="field in data.memberList"
                  :key="field.name"
                  :class="{ 'flex-1': field.name === 'size_id' }">
                  <view v-if="field.name === 'truename'">
                    {{ data.formData.size_list[index].truename }}
                  </view>
                  <!-- 存一个sign_id -->
                  <block v-if="field.name === 'sign_id'">
                    <uni-forms-item :name="['size_list', index, 'sign_id']">
                      <template #label></template>
                    </uni-forms-item>
                  </block>
                  <!-- 尺码 -->
                  <block v-if="field.name === 'size_id'">
                    <uni-forms-item
                      :name="['size_list', index, 'size_id']"
                      :rules="[{ required: true, errorMessage: '尺寸必填' }]">
                      <template #label></template>
                      <uni-data-select
                        :clear="false"
                        v-model="data.formData.size_list[index].size_id"
                        :localdata="data.sizeList"
                        border />
                    </uni-forms-item>
                  </block>
                </view>
              </view>
            </view>
          </view>
        </view>
      </uni-forms>
      <!-- 显示勾选的信息 -->
      <div v-else>
        <view class="item" v-if="data.member_list?.length >= 1">
          <view class="title">成员列表</view>
          <view class="form-item-content">
            <view class="member-list">
              <view class="member-item" style="background: white; margin-bottom: 0">
                <view>姓名</view>
                <view class="p-right-20">尺码</view>
              </view>
              <view class="member-item" v-for="item in data.member_list" :key="item.id">
                <view>{{ item.truename }}</view>
                <view class="p-right-20">{{ item.size }}</view>
              </view>
            </view>
          </view>
        </view>

        <template
          v-if="
            [TeamUserButtonState.中签_已完成, TeamUserButtonState.领取参赛包].includes(data.info.user_button_state)
          ">
          <view class="card">
            <view class="title">{{ data.way == BagWayStatus.线下 ? '现场领取' : '邮寄（快递到付）' }}</view>
            <view class="code-wrap" v-if="data.way == BagWayStatus.线下">
              <view class="left-title" :style="{ background: data.configInfo?.select_color_text }">
                领取装备包二维码
              </view>
              <view v-if="data.is_get_size == 1" class="code-content flex-c red">已核销</view>
              <view v-else class="code-content flex-c">
                <ikun-qrcode width="390" height="390" unit="rpx" color="#000000" :data="data.codeUrl" />
              </view>
            </view>
            <view v-if="data.is_get_size != 1" class="code-tip">此二维码为装备包领取凭证，请妥善保管，切勿泄露或发送给他人。如因二维码泄露导致装备被冒领，概不负责！</view>
            <view v-if="data.way == BagWayStatus.线上" @click="handleInviteCode">
              <uni-easyinput disabled type="textarea" v-model="data.express" placeholder="物流信息" />
            </view>
          </view>
          <view class="card" v-if="data.way == BagWayStatus.线上">
            <view class="title">收货地址</view>
            <view>
              <uni-easyinput disabled type="textarea" v-model="data.address" placeholder="收货地址" />
            </view>
            <view class="title">收件人</view>
            <view>
              <uni-easyinput disabled type="text" v-model="data.addressee" placeholder="收件人" />
            </view>
            <view class="title">联系方式</view>
            <view>
              <uni-easyinput disabled type="text" v-model="data.mobile" placeholder="联系方式" />
            </view>
            <view class="title">邮编</view>
            <view>
              <uni-easyinput disabled type="text" v-model="data.area_code" placeholder="邮编" />
            </view>
          </view>
        </template>
      </div>
    </div>
    
    <md-read-dialog
      ref="readDialogRef"
      :mask-click="false"
      confirm-text="提交"
      :content="readContent"
      :countdown="countdown"
      @confirm="handleConfirmSubmit"
      @cancel="handleCancelSubmit" />
    
    <md-read-dialog
      ref="refundDialogRef"
      :mask-click="false"
      confirm-text="确定退赛"
      :content="refundReadContent"
      :countdown="refundCountdown"
      @confirm="handleConfirmRefund"
      @cancel="handleCancelRefund" />
  </md-page>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import type { BtnTextItem } from '@/components/md-ui/components/md-page/md-page.vue';
import { parseParams, Toast } from '@/utils/util';
// 接口
import { activeDetail, apply_refund, signTeamChooseSize, signTeamSizeInfo, signTeamSizeList } from '@/api';
import type { SignTeam } from '@/api/data';
import { BagWayStatus, TeamUserButtonState } from '@/api/enum';
import { cancelPayOrder, payOrder } from '@/utils/api';
import MdReadDialog from '@/components/md-ui/components/md-read-dialog/md-read-dialog.vue';

// 枚举
enum isRefundButton {
  显示退赛按钮 = 1,
  隐藏退赛按钮 = 2,
}
enum isGetSize {
  已核销 = 1,
  未核销 = 2,
}

type MdReadDialogInstance = InstanceType<typeof MdReadDialog>;

const data = reactive<any>({
  express: '', // 物流信息
  address: '', // 收货地址
  mobile: '', // 收件人号码
  addressee: '', //收件人
  area_code: '', // 邮编
  configInfo: {},
  btnTextItems: [],
  formData: { way: BagWayStatus.线下, size_list: [] },
  memberList: [
    { label: 'ID', name: 'sign_id' },
    { label: '姓名', name: 'truename' },
    { label: '尺码', name: 'size_id' },
  ],
  wayList: [],
  sizeList: [],
  member_list: [],
  codeUrl: '', // 二维码
  is_get_size: 0, // 是否核销
  info: {}, // 传递的参数
  active_id: -1,
  way: 0, // 领取方式
});
const form = ref<any>(null);
const readDialogRef = ref<MdReadDialogInstance | null>(null);
const countdown = ref<number>(5);
const countdownTimer = ref<any>(null);
const pendingSubmitData = ref<any>(null);

// 退赛弹窗相关
const refundDialogRef = ref<MdReadDialogInstance | null>(null);
const refundCountdown = ref<number>(15);
const refundCountdownTimer = ref<any>(null);
// 退赛阅读内容 - 从接口获取
const refundReadContent = ref<string>('');
// 退赛倒计时初始值 - 从接口获取
const initialRefundCountdown = ref<number>(15);

// 阅读内容 - 从接口获取
const readContent = ref<string>('');
// 倒计时初始值 - 从接口获取
const initialCountdown = ref<number>(5);

// 全局配置按钮的颜色处理
const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
data.configInfo = configInfo;
let commonStyle = (type: number) => ({
  color: configInfo?.['button_color' + type] || '#1CA4C0',
  textColor: configInfo?.['button_color' + type + '_text'] || '#ffffff',
});

// 启动倒计时
const startCountdown = () => {
  countdown.value = initialCountdown.value;
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
  countdownTimer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value);
      countdownTimer.value = null;
    }
  }, 1000);
};

// 获取活动详情（用于获取阅读内容和倒计时时间）
const fetchActiveDetailForReadContent = async (active_id: number) => {
  if (!active_id || active_id === -1) return;
  try {
    const res = await activeDetail({ active_id });
    const detailData = res.data as any;
    
    // 获取提交阅读内容
    if (detailData?.pay_tips) {
      readContent.value = detailData.pay_tips;
    }
    
    // 获取提交倒计时初始值
    if (detailData?.pay_read_time) {
      initialCountdown.value = Number(detailData.pay_read_time) || 5;
      // 如果当前倒计时还在使用默认值，更新它
      if (countdown.value === 5 && initialCountdown.value !== 5) {
        countdown.value = initialCountdown.value;
      }
    }
    
    // 获取退赛阅读内容
    if (detailData?.refund_tips) {
      refundReadContent.value = detailData.refund_tips;
    }
    
    // 获取退赛倒计时初始值
    if (detailData?.refund_read_time) {
      initialRefundCountdown.value = Number(detailData.refund_read_time) || 15;
      // 如果当前倒计时还在使用默认值，更新它
      if (refundCountdown.value === 15 && initialRefundCountdown.value !== 15) {
        refundCountdown.value = initialRefundCountdown.value;
      }
    }
  } catch (error) {
    console.error('获取活动详情失败:', error);
  }
};

// 确认提交
const handleConfirmSubmit = () => {
  
  if (countdown.value > 0) {
    uni.showToast({
      title: `请等待${countdown.value}秒`,
      icon: 'none',
      duration: 2000
    });
    return false; // 阻止关闭弹窗
  }
  
  readDialogRef.value?.close();
  
  if (pendingSubmitData.value) {
    fetchSignTeamChooseSize({ ...pendingSubmitData.value });
    pendingSubmitData.value = null;
  }
  
  // 清理定时器
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
  
  return true;
};

// 取消提交
const handleCancelSubmit = () => {
  // 关闭弹窗
  if (readDialogRef.value) {
    readDialogRef.value.close();
    data.btnTextItems = [
      {
        text: '确认并付款',
        key: 'submit',
        ...commonStyle(1),
      },
    ];
  }
  
  // 清理数据
  pendingSubmitData.value = null;
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
  countdown.value = initialCountdown.value;
};

// 启动退赛倒计时
const startRefundCountdown = () => {
  refundCountdown.value = initialRefundCountdown.value;
  if (refundCountdownTimer.value) {
    clearInterval(refundCountdownTimer.value);
  }
  refundCountdownTimer.value = setInterval(() => {
    refundCountdown.value--;
    if (refundCountdown.value <= 0) {
      clearInterval(refundCountdownTimer.value);
      refundCountdownTimer.value = null;
    }
  }, 1000);
};

// 确认退赛
const handleConfirmRefund = () => {
  if (refundCountdown.value > 0) {
    uni.showToast({
      title: `请等待${refundCountdown.value}秒`,
      icon: 'none',
      duration: 2000
    });
    return false; // 阻止关闭弹窗
  }
  
  refundDialogRef.value?.close();
  
  // 清理定时器
  if (refundCountdownTimer.value) {
    clearInterval(refundCountdownTimer.value);
    refundCountdownTimer.value = null;
  }
  
  // 执行退赛
  fetchApplyRefund();
  return true;
};

// 取消退赛
const handleCancelRefund = () => {
  // 关闭弹窗
  if (refundDialogRef.value) {
    refundDialogRef.value.close();
    data.btnTextItems = [
    {
        text: '申请退赛',
        key: 'refund',
        ...commonStyle(2)
      }]
  }
  
  // 清理定时器
  if (refundCountdownTimer.value) {
    clearInterval(refundCountdownTimer.value);
    refundCountdownTimer.value = null;
  }
  refundCountdown.value = initialRefundCountdown.value;
};

// 底部功能按钮回调
const bottomBtnClick = async (info: { item: BtnTextItem }) => {
  const { key } = info.item;
  // 确认并付款
  if (key === 'submit') {
    try {
      const vals = await form.value?.validate();
      pendingSubmitData.value = vals;
      data.btnTextItems = [];
      // 启动倒计时并显示弹窗
      startCountdown();
      readDialogRef.value?.open();
    } catch (error) {}
  }

  // 支付
  if (key === 'pay') {
    payOrder(
      {
        order_id: data.payInfo.order_id || '',
        order_sn: data.payInfo.order_sn || '',
      },
      (type: 'success' | 'fail') => {
        const msg = type === 'success' ? '支付成功' : '用户取消支付';
        uni.showModal({
          title: '提示',
          content: msg,
          showCancel: false,
          success: async res => {
            if (res.confirm) {
              uni.switchTab({ url: '/pages/index/index' });
            }
          },
        });
      }
    );
  }

  // 取消支付
  if (key === 'cancel_pay') {
    cancelPayOrder({
      order_id: data.payInfo.order_id || '',
      order_sn: data.payInfo.order_sn || '',
    });
  }

  // 退赛
  if (key === 'refund') {
    // 启动倒计时并显示退赛阅读弹窗
    data.btnTextItems = [];
    startRefundCountdown();
    refundDialogRef.value?.open();
  }
};

// 去选择地址
const addrClick = () => {
  uni.navigateTo({
    url: '/pages/other/address/address-manage/index?type=select',
  });
};

/**
 * 接口相关
 */
// 获取尺码及报名用户列表
const fetchSignTeamSizeList = async (active_id: string) => {
  try {
    const res = await signTeamSizeList({
      active_id,
    });
    // 领取方式
    data.wayList = Object.entries(res.data?.way_list || {})?.map(([value, text]) => ({
      text,
      value: +value,
    }));
    // 带库存的数量的尺码列表
    data.sizeList = res.data?.size_list?.map(item => ({
      text: `${item?.name || ''}(${item?.rest_inventory || 0})`,
      value: item?.id,
    }));
    // 报名人列表
    data.formData.size_list = res.data?.member_list?.map(item => ({
      sign_id: item.id,
      truename: item.truename,
    }));
    // 底部操作按钮
    data.btnTextItems = [
      {
        text: '确认并付款',
        key: 'submit',
        ...commonStyle(1),
      },
    ];
  } catch (error) {}
};

// 提交
const fetchSignTeamChooseSize = async (params: Omit<SignTeam.ChooseSize.Body, 'active_id'>) => {
  try {
    const res = await signTeamChooseSize({
      active_id: data.active_id,
      ...params,
      addr: data.addrInfo,
    });

    // 需要支付费用
    if (res.data.is_charge == 1) {
      payOrder(res.data, type => {
        const msg = type === 'success' ? '支付成功' : '用户取消支付';
        uni.showModal({
          title: '提示',
          content: msg,
          showCancel: false,
          success: res => {
            if (res.confirm) {
              uni.switchTab({ url: '/pages/index/index' });
            }
          },
        });
      });
    } else {
      uni.showModal({
        title: '提示',
        content: res?.msg || '提交成功',
        showCancel: false,
        success: res => {
          if (res.confirm) {
            uni.switchTab({ url: '/pages/index/index' });
          }
        },
      });
    }
  } catch (error) {}
};

// 复制快递单号
const handleInviteCode = () => {
  uni.setClipboardData({
    data: data.express,
    success: function () {
      Toast('物流信息复制成功');
    },
  });
};

// 获取已勾选尺码的信息
const fetchSignTeamSizeInfo = async (active_id?: string, user_button_state?: TeamUserButtonState) => {
  try {
    const res = await signTeamSizeInfo({
      active_id: active_id || data?.active_id,
    });
    data.member_list = res.data?.member_list;
    data.codeUrl = `signid=${res.data?.sign_id}&end`;
    data.is_get_size = res.data?.is_get_size;
    data.express = res.data?.express || '';
    data.address = res.data?.address?.address || '';
    data.mobile = res.data?.address?.mobile || '';
    data.addressee = res.data?.address?.name || '';
    data.area_code = res.data?.address?.area_code || '';
    data.way = res.data?.way || 0;
    data.payInfo = res.data?.order_info || {};

    const _user_button_state = user_button_state || data?.info?.user_button_state || '';

    data.btnTextItems = [
      {
        text: '确认并付款',
        key: 'submit',
        hide: _user_button_state != TeamUserButtonState.选择尺码 || data.way > 0,
        ...commonStyle(1),
      },
      {
        text: '支付',
        key: 'pay',
        hide: !!res.data?.is_paid,
        ...commonStyle(1),
      },
      {
        text: '取消支付',
        key: 'cancel_pay',
        hide: !!res.data?.is_paid,
        ...commonStyle(2),
      },
      {
        text: '申请退赛',
        key: 'refund',
        hide:
          res.data?.is_get_size == isGetSize.已核销 ||
          res.data?.is_refund_button == isRefundButton.隐藏退赛按钮 ||
          _user_button_state == TeamUserButtonState.领取参赛包,
        ...commonStyle(2),
      },
    ];
  } catch (error) {}
};

// 退赛
const fetchApplyRefund = async () => {
  try {
    const res = await apply_refund({ active_id: data.active_id });
    uni.showModal({
      title: '提示',
      content: res?.msg || '退赛成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.switchTab({ url: '/pages/index/index' });
        }
      },
    });
  } catch (error) {}
};

// 下拉刷新
const handlePullDownRefresh = () => {
  fetchSignTeamSizeInfo(data?.active_id, data?.user_button_state);
};

onLoad(option => {
  const query = parseParams(option?.params);
  console.log(query);
  data.active_id = query?.active_id;
  data.info = query;
  
  // 获取活动详情中的阅读内容和倒计时时间
  if (query?.active_id) {
    fetchActiveDetailForReadContent(Number(query.active_id));
  }
  
  if (query.user_button_state == TeamUserButtonState.选择尺码) {
    fetchSignTeamSizeList(query?.active_id);
  } else {
    fetchSignTeamSizeInfo(query?.active_id, query?.user_button_state);
  }
});

onShow(() => {
  const selAddrInfo = uni.getStorageSync('selectAddress') ? JSON.parse(uni.getStorageSync('selectAddress')) : undefined;
  if (selAddrInfo) {
    data.formData.addr = `${selAddrInfo.province}${selAddrInfo.city}${selAddrInfo.district}${selAddrInfo.address}`;
    data.addrInfo = selAddrInfo;
    uni.removeStorageSync('selectAddress');
  }
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  height: auto;
  display: flex;
  flex-direction: column;
  .item {
    background: white;
    padding: 26rpx 30rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
  }
  ::v-deep {
    .uni-forms-item {
      margin-bottom: 0;
    }
  }
  .forms-item-label {
    height: 36px;
    line-height: 36px;
    padding-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
  .member-list {
    .member-item {
      width: 100%;
      height: 80rpx;
      background: #f7f7f7;
      border-radius: 10rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-left: 24rpx;
      box-sizing: border-box;
      &:not(:last-of-type) {
        margin-bottom: 30rpx;
      }
      ::v-deep {
        .uni-select {
          border: 0;
        }
      }
    }
  }
  .custom-checkbox {
    ::v-deep {
      .uni-data-checklist .checklist-group {
        flex-direction: column !important;
        gap: 12rpx 12rpx;
      }
    }
  }
  .title {
    font-weight: bold;
    font-size: 40rpx;
    margin-bottom: 20rpx;
  }
  // 详情相关样式
  .card {
    padding: 26rpx 30rpx;
    box-sizing: border-box;
    background: white;
  }
  .code-wrap {
    display: flex;
    width: 100%;
    height: 460rpx;
    border-radius: 20rpx;
    overflow: hidden;
    & > .left-title {
      font-size: 34rpx;
      font-weight: bold;
      width: 80rpx;
      background: $primary;
      color: white;
      text-align: center;
      padding: 14rpx;
      box-sizing: border-box;
      display: flex;
      align-items: center;
    }
    & > .code-content {
      flex: 1;
      background: #f7f7f7;
    }
    & > .red {
      color: red;
      font-size: 30rpx;
    }
  }
  .code-tip {
    margin-top: 20rpx;
    padding: 20rpx 28rpx;
    border-radius: 16rpx;
    color: #d92121;
    font-size: 34rpx;
    font-weight: 600;
  }
}

</style>
